<?php
namespace app\common\model\food;

use app\common\model\BaseModel;
use think\facade\Db;
use hema\device\Driver;

/**
 * 云设备模型
 */
class Device extends BaseModel
{
    // 定义表名
    protected $name = 'food_device';

    // 定义主键
    protected $pk = 'device_id';

    // 追加字段
    protected $append = [
        'status'
    ];

    /**
     * 类型
     */
    public function getDevTypeAttr($value)
    {
        $status = [
            'feieyun' => '飞鹅云打印机', 
            'yilianyun' => '易联云打印机', 
            'daqu' => '大趋云打印机',
            'hmcalling' => '河马云叫号器'
        ];
        return ['text' => $status[$value], 'value' => $value];
    }
    
    /**
     * 关联门店表
     */
    public function shop()
    {
        return $this->belongsTo('app\\common\\model\\food\\Shop','shop_id');
    }

    /**
     * 状态
     */
    public function getIsOpenAttr($value)
    {
        $status = ['关闭','开启'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 获取器: 转义数组格式
     */
    public function getValuesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 修改器: 转义成json格式
     */
    public function setValuesAttr($value)
    {
        return json_encode($value);
    }

    /**
     * 设备联网状态 - 自动完成
     * 返回数据格式："}{"State":0,"Code":200,"Message":"成功"}
     *State:状态值(-1错误 0正常 1缺纸 2温度保护报警 3 忙碌 4 离线)
     */
    public function getStatusAttr($value,$data)
    {
        $dev = new Driver($data['dev_type']);
        return $dev->status($data['dev_id']);
    }

    /**
     * 获取列表
     */
    public function getList($shop_id = 0,$is_open = null)
    {
        $filter = [];// 筛选条件
        $shop_id > 0 && $filter['shop_id'] = $shop_id;
        !is_null($is_open) && $filter['is_open'] = $is_open;
        // 排序规则
        $sort = ['device_id' => 'desc']; 
         // 执行查询
        return $this->with(['shop'])->where($filter)->order($sort)->select();
    }

    /**
     * 播报语音
     * $mode = 模式(new=新订单提醒,pay=微信到账提醒) ，$row_no=参数,
     */
    public static function push($shop_id=0,$mode,$row_no='')
    {
        // 筛选条件
        $filter = [
            'dev_type' => 'hmcalling',
            'is_open' => 1
        ];
        $shop_id > 0 && $filter['shop_id'] = $shop_id;
        if($call = self::get($filter)){
            if($mode == 'pay' AND $call['values']['is_pay'] == 0){
                return true; //未开启直接退出
            }
            if($mode == 'new' AND $call['values']['is_new'] == 0){
                return true; //未开启直接退出
            }
            $dev = new Driver('hmcalling');
            $dev->push([
                'dev_id' => $call['dev_id'],
                'mode' => $mode,
                'row_no' => $row_no
            ]);
        }
        return true;
    }

    /**
     * 打印小票
     * $data 打印的数据
     * $tpl 模板类型 0=订单模板 1=退单模板
     */
    public static function print($data, $tpl=0)
    {
        // 筛选条件
        $filter = ['is_open' => 1];
        if(isset($data['shop_id']) AND $data['shop_id'] > 0){
            $filter['shop_id'] = $data['shop_id'];
        }
        //获取门店打印机列表
        if($list = self::where($filter)->where('dev_type','<>','hmcalling')->select()){
            //如果有设备
            foreach ($list as $item){
                //筛选打印商品订单列表
                if(isset($item['values']['category'])){
                    $goods = [];//筛选后的商品目录
                    //循环订单商品
                    for ($n = 0; $n < sizeof($data['goods']); $n++) {
                        foreach ($item['values']['category'] as $vo) {
                            //判断是否在打印类目中
                            if($data['goods'][$n]['goods']['category_id'] == $vo){
                                $goods[] = $data['goods'][$n];
                            }
                        }
                    }
                    if(sizeof($goods) == 0){
                        return true;//没有要打印的内容
                    }else{
                        $data['goods'] = $goods;//更新打印商品列表
                    }
                } 
                $content = [];//生成的打印模板
                if($tpl == 1){
                    //退单模板
                    if($data['order_mode']['value']==10){
                        if(isset($data['table']['table_name'])){
                            $title = $data['table']['table_name'];
                        }else{
                            $title = '堂食'.$data['row_no'].'号';
                        }
                    }
                    if($data['order_mode']['value']==20){
                        $title = '外卖'.$data['row_no'].'号';
                    }
                    if($data['order_mode']['value']==30){
                        $title = '自取'.$data['row_no'].'号';
                    }
                    $content[] = '# 退单 #,<B>,<C>';
                    $content[] = '- '.$title.' -,<B>,<C>';
                    $content[] = str_repeat('-', 32);
                    $content[] = $data['shop']['shop_name'].',<C>';
                    $content[] = "名称        数量,<B>";//16=4+8+4
                    $content[] = str_repeat('-', 32);
                    //循环拼接打印模板
                    for($i = 0; $i < sizeof($data['goods']); $i++) {
                        if($data['goods'][$i]['refund_num']>0){
                            $goods_name = $data['goods'][$i]['goods_name'];//产品名字
                            !empty($data['goods'][$i]['goods_attr']) && $goods_name .= "/" . $data['goods'][$i]['goods_attr'];
                            $refund_num = $data['goods'][$i]['refund_num']; //产品数量
                            //设置名称字符长度
                            $lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
                            for($n=$lan;$n<13;$n++){
                                $goods_name .= ' ';
                            }
                            $content[] = $goods_name . '×' . $refund_num.",<B>";
                        }
                    }
                    $content[] = str_repeat('-', 32);
                    $content[] = '支付金额：￥'.$data['pay_price'];
                    $content[] = '退款金额：￥'.$data['refund_price'];
                    $content[] = '退款理由：'.$data['refund_desc'];
                    $content[] = "# 退单 # 完,<B>,<C>";
                }else{
                    //订单模板
                    if($data['order_mode']['value']==10){
                        if(isset($data['table']['table_name'])){
                            $title = $data['table']['table_name'];
                        }else{
                            $title = '堂食'.$data['row_no'].'号';
                        }
                    }
                    if($data['order_mode']['value']==20){
                        $title = '外卖'.$data['row_no'].'号';
                    }
                    if($data['order_mode']['value']==30){
                        $title = '自取'.$data['row_no'].'号';
                    }
                    $content[] = '# '.$title.' #,<B>,<C>';
                    if($data['arrive_time']['value']>0){
                        $content[] = '到店时间:'.$data['arrive_time']['text'];
                    }
                    $content[] = str_repeat('-', 32);
                    $content[] = $data['shop']['shop_name'].',<C>';
                    if($data['pay_status']['value'] != 30){
                        if($data['transaction_id']){
                            $content[] = '-- 微信支付 --,<C>';
                        }else{
                            $content[] = '-- 余额支付 --,<C>';
                        }
                        $content[] = '支付时间:' . datetime($data['pay_time']);
                    }else{
                        $content[] = '-- 后付款 --,<C>';
                    }
                    $content[] = "名称        数量,<B>";//16=4+8+4
                    $content[] = str_repeat('-', 32);
                    //循环拼接打印模板
                    for ($i = 0; $i < sizeof($data['goods']); $i++) {
                            $goods_name = $data['goods'][$i]['goods_name'];//产品名字
                            !empty($data['goods'][$i]['goods_attr']) && $goods_name .= "/" . $data['goods'][$i]['goods_attr'];
                            $total_num = $data['goods'][$i]['total_num'];   //产品数量
                            //设置名称字符长度
                            $lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
                            for($n=$lan;$n<13;$n++){
                                $goods_name .= ' ';
                            }
                            $content[] = $goods_name . '×' . $total_num . ",<B>";
                    }
                    $content[] = str_repeat('-', 32);
                    $content[] = '商品金额：+￥'.$data['total_price'];
                    if($data['express_price']>0){
                        $content[] = '配送费用：+￥'.$data['express_price'];
                    }
                    if($data['pack_price']>0){
                        $content[] = '餐盒费用：+￥'.$data['pack_price'];
                    }
                    if($data['ware_price']>0){
                        $content[] = '餐具调料：+￥'.$data['ware_price'];
                    }
                    if($data['activity_price']>0){
                        $content[] = '优惠金额：-￥'.$data['activity_price'];
                    }
                    $content[] = '实付金额：￥' . $data['pay_price'];
                    if(empty($data['flavor'])){
                        $content[] = '口味要求：' . $data['flavor'];
                    }
                    if(empty($data['message'])){
                        $content[] = '顾客留言：' . $data['message'];
                    }
                    if($data['order_mode']['value']==20){
                        $content[] = '配送地址：' . $data['address']['detail'];
                        $content[] = '接 收 人：' . $data['address']['name'].$data['address']['phone'];
                    }
                    $content[] = '# ' . $title . ' # 完,<B>,<C>';
                $dev = new Driver($item['dev_type']['value']);
                $device = [
                    'tpl' => $tpl,
                    'dev_id' => $item['dev_id'],//打印机编号
                    'prt_num' => $item['values']['prt_num'], //打印分数
                ];
                $dev->print($device,$content);
            }
            }
        }
        return true;
    }
    
    /**
     * 用户设备绑定
     */
    public function add($data)
    {
        $data['applet_id'] = self::$applet_id;
        // 开启事务
        Db::startTrans();
        try {
            //飞鹅
            if($data['dev_type']=='feieyun'){
                //查询设备是否已经添加
                if($this->get([
                    'dev_id' => $data['dev_id'],
                    'dev_type' => 'feieyun'
                ])){
                    $this->error = '该设备已被添加，不可重复';
                    return false;
                }
                $dev = new Driver('feieyun');
                if(!$result = $dev->add($data)){
                    $this->error = $dev->getError();
                    return false;
                }
            }
            //易联云
            if($data['dev_type']=='yilianyun'){
                //查询设备是否已经添加
                if($this->get([
                    'dev_id' => $data['dev_id'],
                    'dev_type' => 'yilianyun'
                ])){
                    $this->error = '该设备已被添加，不可重复';
                    return false;
                }
                $dev = new Driver('yilianyun');
                if(!$result = $dev->add($data)){
                    $this->error = $dev->getError();
                    return false;
                }
            }
            //大趋
            if($data['dev_type']=='daqu'){
                //查询设备是否已经添加
                if($this->get([
                    'dev_id' => $data['dev_id'],
                    'dev_type' => 'daqu'
                ])){
                    $this->error = '该设备已被添加，不可重复';
                    return false;
                }
                $dev = new Driver('daqu');
                if(!$result = $dev->add($data)){
                    $this->error = $dev->getError();
                    return false;
                }
            }
            //云叫号
            if($data['dev_type']=='hmcalling'){
                //查询设备是否已经添加
                if($this->get([
                    'dev_id' => $data['dev_id'],
                    'dev_type' => 'hmcalling'
                ])){
                    $this->error = '该设备已被添加，不可重复';
                    return false;
                }
                if($this->get([
                    'shop_id' => $data['shop_id'],
                    'dev_type' => 'hmcalling'
                ])){
                    $this->error = '每个门店只能添加一台！';
                    return false;
                }
                $dev = new Driver('hmcalling');
                if(!$result = $dev->add($data)){
                    $this->error = $dev->getError();
                    return false;
                }
            }
            $this->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 更新
     */
    public function edit($data)
    {
        //云叫号器
        if($this['dev_type']['value'] == 'hmcalling' AND $this['values']['volume'] != $data['values']['volume']){
            $dev = new Driver('hmcalling');
            if(!$result = $dev->push([
                'dev_id' => $this->dev_id,
                'mode' => 'volume',
                'row_no' => $data['values']['volume']
            ])){
                $this->error = $dev->getError();
                return false;
            }
        }
        return $this->save($data) !== false;
    }

    /**
     * 删除
     */
    public function remove() {
         //飞鹅
        if($this['dev_type']['value'] == 'feieyun'){
            $dev = new Driver('feieyun');
            if(!$result = $dev->delete($this->dev_id)){
                $this->error = $dev->getError();
                return false;
            }
        }
        //易联云
        if($this['dev_type']['value'] == 'yilianyun'){
            $dev = new Driver('yilianyun');
            if(!$result = $dev->delete($this->dev_id)){
                $this->error = $dev->getError();
                return false;
            }
        }
        //大趋
        if($this['dev_type']['value'] == 'daqu'){
            $dev = new Driver('daqu');
            if(!$result = $dev->delete($this->dev_id)){
                $this->error = $dev->getError();
                return false;
            }
        }
        //河马云叫号
        if($this['dev_type']['value'] == 'hmcalling'){
            $dev = new Driver('hmcalling');
            if(!$result = $dev->delete($this->dev_id)){
                $this->error = $dev->getError();
                return false;
            }
        }
        return $this->delete();
    }

    /**
     * 状态
     */
    public function statu()
    {
        $this->is_open['value'] ? $this->is_open = 0 : $this->is_open = 1;
        return $this->save();
    }
}